<?php
namespace Data;

use Out;

class Filter extends \Data
{
    public static function Run(&$data, $form)
    {
        $rules = self::getRules($form);
        foreach ($data as $key => $value) {
            $value = preg_replace("/\r?\n?\"?'?/", "", $value);
            if (!isset($rules[$key])) {
                unset($data[$key]);
                continue;
            }
            if (preg_match("/\)or\(/", $rules[$key]['rules'])) {
                $rules[$key]['rules'] = explode('or', $rules[$key]['rules'])[0];
            }
            if (empty($rules[$key]['rules']) || $rules[$key]['rules'] == '') {
                continue;
            }
            if (!preg_match("/{$rules[$key]['rules']}/", $value)) {
                Out::Error($rules[$key]['msg']);
            }
        }
    }

    public static function getRules($form)
    {
        $rules = [];
        foreach ($form as $value) {
            if (!isset($value['name'])) {
                $rules = array_merge($rules, self::getRules($value));
            } else if (!isset($value['dis']) || $value['dis'] == 'save') {
                $rules[$value['name']] = $value;
            }
        }
        return $rules;
    }
}
